package com.egdigital.allzic.ui.fragment;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.egdigital.allzic.R;
import com.egdigital.allzic.data.json.JsonCallBack;
import com.egdigital.allzic.data.json.JsonParserStation;
import com.egdigital.allzic.data.json.VolleyManager;
import com.egdigital.allzic.data.object.Station;
import com.egdigital.allzic.service.DownloadState;
import com.egdigital.allzic.ui.activity.ActivityMain;
import com.egdigital.allzic.ui.adapter.AdapterListRadio;
import com.egdigital.allzic.utils.NetworkManager;

public class FragmentCategoryNational extends BaseMainFragment implements OnClickListener, OnItemClickListener {

	private static final String	TAG				= FragmentCategoryNational.class.getSimpleName();			// log
	private static String		URL_NATIONAL	= "http://www.allzicradio.com/fr/json/get_all/%s/%s/%s/%s"; // url to get all national radio (france only)
	private List<Station>		mList;
	private JsonParserStation	mJsonParserStation;
	private int					mCurrentPage	= 0;
	//
	private AdapterListRadio	mAdapter;
	private LoadMoreListView	mListView;
	private ImageButton			mcloseButton;
	private TextView			mTitle;
	//
	protected ActivityMain		mParent;
	protected View				mView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_list_radio_more, container, false);
		mLoadingView = (RelativeLayout) mView.findViewById(R.id.fragment_radio_loading);
		mReloadView = (LinearLayout) mView.findViewById(R.id.fragment_radio_reload);
		mNoResultView = (TextView) mView.findViewById(R.id.fragment_radio_noresult);
		//
		mTitle = (TextView) mView.findViewById(R.id.fragment_categoryradio_more_title);
		mListView = (LoadMoreListView) mView.findViewById(R.id.fragment_categoryradio_more_list);
		mcloseButton = (ImageButton) mView.findViewById(R.id.fragment_categoryradio_more_close);
		return mView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		mListView.setOnItemClickListener(this);
		mcloseButton.setOnClickListener(this);
		mReloadView.setOnClickListener(this);
		mTitle.setText(getString(R.string.fragment_category_national));
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public void onResume() {
		// Analytics
		analyticsSendEvent("National");
		VolleyManager.init(mParent);
		if (mJsonParserStation == null) {
			mJsonParserStation = new JsonParserStation();
			setCallBacks();
		}
		if (mList == null || mList.isEmpty()) {
			mJsonParserStation.initAndStartRequestQueue();
		} else {
			updateAdapter(mList);
		}
		super.onPause();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.fragment_radio_reload:
				if (mList != null && !mList.isEmpty()) {
					mList.clear();
				}
				if (!mDownloadState.equals(DownloadState.LOADING)) {
					loadData();
				}
				break;
			case R.id.fragment_categoryradio_more_close:
				mParent.removeFragment();
				break;
		}
	}

	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		if (mParent != null) {
			Station station = mList.get(position);
			mParent.prepareToPlay(station);
			mParent.showPlayerBanner();
			mParent.updatePlayerBanner();
		}
	}

	/**
	 * animation
	 */
	@SuppressLint("NewApi")
	@Override
	public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
		Animation animation = super.onCreateAnimation(transit, enter, nextAnim);
		if (animation == null && nextAnim != 0) {
			animation = AnimationUtils.loadAnimation(getActivity(), nextAnim);
		}
		if (animation != null) {
			getView().setLayerType(View.LAYER_TYPE_HARDWARE, null);
			animation.setAnimationListener(new AnimationListener() {

				public void onAnimationEnd(Animation animation) {
					getView().post(new Runnable() {

						@Override
						public void run() {
							loadData();
						}
					});
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationStart(Animation animation) {
				}
			});
		}
		return animation;
	}

	/**
	 * fragment life cycle
	 */
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mParent = (ActivityMain) activity;
	}

	@Override
	public void onDetach() {
		if (mJsonParserStation != null) {
			mJsonParserStation.stopRequestQueue();
		}
		mParent = null;
		super.onDetach();
	}

	/**
	 * methods
	 */
	private void loadData() {
		if (NetworkManager.isConnected(mParent.getApplicationContext())) {
			mJsonParserStation.extractJsonObjectData(String.format(URL_NATIONAL, 0, mCurrentPage, 50, "nationale"));
		} else {
			setReload(mListView);
		}
	}

	private void setCallBacks() {
		mJsonParserStation.setJsonCallBack(new JsonCallBack() {

			@Override
			public void downloadStarted() {
				if (mCurrentPage == 0) {
					setLoading(mListView);
				}
			}

			@Override
			public void downloadPercent(int percent) {
			}

			@Override
			public void downloadEndedWithError(VolleyError error) {
				setReload(mListView);
			}

			/**
			 * Will display all station in the list
			 */
			@Override
			public <T> void downloadCompleted(List<T> list) {
				if (mParent == null || list == null) {
					return;
				}
				if (!list.isEmpty()) {
					if (mList != null && mList.size() != list.size()) {
						mList.addAll((List<Station>) list);
					} else {
						mList = (List<Station>) list;
					}
					// sort
					Collections.sort(mList, new Comparator<Object>() {

						public int compare(Object o1, Object o2) {
							Station p1 = (Station) o1;
							Station p2 = (Station) o2;
							return p1.getmTitle().compareToIgnoreCase(p2.getmTitle());
						}
					});
					updateAdapter(mList);
				} else if (mList == null || mList.isEmpty()) {
					setNoResult(mListView);
				} else {
					setLoaded(mListView);
				}
				mListView.onLoadMoreComplete();
			}
		});
		/**
		 * Callback used by Volley when the download and parsing of places around the given lat and lng is done
		 */
		mListView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				mCurrentPage++;
				loadData();
			}
		});
	}

	private void updateAdapter(List<Station> list) {
		if (mAdapter == null) {
			mAdapter = new AdapterListRadio(mParent.getApplicationContext(), list, R.layout.cell_list_radio);
			mListView.setAdapter(mAdapter);
			mListView.setSelection(0);
		} else {
			mAdapter.setData(list);
			mAdapter.notifyDataSetChanged();
		}
		setLoaded(mListView);
		mListView.setOnItemClickListener(this);
	}
}
